<template>
    <div class="mapbox" v-if="showMap">
        <div id="container" v-if="showMap" v-loading="loading"></div>
        <div class="scbox">
            <input type="text" id="suggestId" size="20" value="" placeholder="输入关键字搜索" />
        </div>
    </div>
</template>

<script>
import map from '@/utils/map.js'
export default {
    props:{
        showMap:{
            type:Boolean,
            default:false
        },
        center:String,
        point:{
            type:Object,
            default:{}
        },
    },
    components:{
        
    },
    data(){
        return{
            map:null,
            findData:'',
            keyword:'',
            loading:true
        }
    },
    async created(){
        await map.init() 
        this.createMap()
    },
    methods:{
        async createMap(){
            const ret = await this.getPositionInfo()
            const point = new BMapGL.Point(ret.center.lng, ret.center.lat)

            this.map = new BMapGL.Map("container"); 
            this.map.enableScrollWheelZoom(true); // 开启鼠标滚轮缩放
            if(this.point.lng && this.point.lat){
                const pt = new BMapGL.Point(this.point.lng, this.point.lat)
                this.map.centerAndZoom(pt,15);
                this.map.addOverlay(new BMapGL.Marker(pt));    //添加标注
            }else if(this.center){
                this.map.centerAndZoom(this.center,15)
            }else{
                this.map.centerAndZoom(point,15); // 初始化地图,设置中心点坐标和地图级别   
            }
            this.createSearch()
            this.addClick()  // 添加点击事件

            this.map.addEventListener('tilesloaded',  ()=> {
                console.log('地图加载完成！');
                this.loading = false
                this.$emit('loaded',this.map)
            });
        },
        // 获取当前位置信息（只获取到城市）
        getPositionInfo(){
            return new Promise((resolve,reject)=>{
                let myCity = new BMapGL.LocalCity()
                myCity.get(function (result) {
                    resolve(result)
                }) 
            })        
        },
        createSearch(){
            const ac = new BMapGL.Autocomplete(    //建立一个自动完成的对象
                {
                    "input" : "suggestId",
                    "location" : this.map
                }
            );
            ac.addEventListener('onconfirm',(e)=>{ 
                //this.map.clearOverlays()//清除地图上所有覆盖物
                const _value = e.item.value;
                console.log('_value:',_value)
		        const myValue = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
                this.keyword = _value.district +  _value.street +  _value.business

                //ac.setInputValue(myValue);

                this.map.clearOverlays();    //清除地图上所有覆盖物
                const local = new BMapGL.LocalSearch(this.map, { //智能搜索
                    onSearchComplete: ()=>{
                        const pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
                        //console.log("pp:",pp)
                        this.map.centerAndZoom(pp, 18);
                        this.map.addOverlay(new BMapGL.Marker(pp));    //添加标注
                    }
                });
                local.search(myValue)
            })
        },
        addClick(){
            this.map.addEventListener("click", async (e)=>{  
                if(!this.keyword){
                   this.keyword = await this.getAddressForlnglat(e.latlng.lng,e.latlng.lat)
                }
                this.$confirm(`当前点击位置经纬度：<p>${e.latlng.lng}，${e.latlng.lat}</p>`, '提示', {
                    dangerouslyUseHTMLString:true,
                    confirmButtonText: '立即使用',
                    cancelButtonText: '取消',
                    type: 'success '
                }).then(() => {
                    this.$emit('getPoint',{address:this.keyword,lng:e.latlng.lng,lat:e.latlng.lat}) 
                }).catch(() => {
                    console.log('cancel')
                });  
            });
        },
        getAddressForlnglat(lng,lat){  //  根据经纬度获取地址信息
            return new Promise((resolve,reject) =>{
                const point = new BMapGL.Point(lng, lat);
                const getData = new BMapGL.Geocoder();
                getData.getLocation(point, function(rs){
                    const info = rs.addressComponents;
                    resolve(info.city+info.district+info.street)
                });
            })
        }
    }
}
</script>

<style lang="scss" scoped>
    #container{
        width: 100%;
        height: 500px;
    }
    .mapbox{
        position: relative;
        z-index: 10;
        .scbox{
            background: #eee;
            position: absolute;
            z-index: 10;
            top: 0;
            right: 0;
            input{
                border: 1px solid #ddd;
                height: 40px;
                line-height: 26px;
                width: 400px;
                padding: 0 15px;
            }
        }
    }
</style>
<style>
    .tangram-suggestion-main{
        z-index: 8000;
    }
</style>